/* EasyWay Game Engine
 * Copyright (C) 2007 Daniele Paggi.
 *  
 * Written by: 2007 Daniele Paggi<dshnt@hotmail.com>
 *   
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public License
 * as published by the Free Software Foundation; either version 2 of
 * the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Library General Public License for more details.
 * 
 * You should have received a copy of the GNU Library General Public
 * License along with this program; if not, write to the Free Software
 * Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 */
package org.easyway.editor.forms.components;

import java.util.ArrayList;

import org.easyway.editor.forms.components.interfaces.IEnable;
import org.easyway.editor.forms.components.interfaces.IValidity;

public class Group {

	public static ArrayList<IValidity> AllObjects = new ArrayList<IValidity>(20);

	public static IValidity searchFromName(String name) {
		for (IValidity it : AllObjects) {
			if (it.getName().equals(name)) {
				return it;
			}
		}
		return null;
	}

	// -----------------------

	protected ArrayList<IValidity> list;

	protected ArrayList<IEnable> listEnablable;

	public Group() {
		list = new ArrayList<IValidity>(20);
		listEnablable = new ArrayList<IEnable>(20);
		checkValidity();
	}

	public void add(IValidity it) {
		list.add(it);
		checkValidity();
		it.getGroups().add(this);
	}

	public void add(IValidity... lit) {
		for (IValidity it : lit)
			list.add(it);
		checkValidity();
		for (IValidity it : lit)
			it.getGroups().add(this);
	}

	public void addEnable(IEnable ie) {
		listEnablable.add(ie);
		ie.setEnabled(false);
		checkValidity();
	}

	public IValidity search(String name) {
		for (IValidity it : list) {
			if (it.getName().equals(name)) {
				return it;
			}
		}
		return null;
	}

	public void remove(IValidity it) {
		list.remove(it);
		checkValidity();
	}

	public void removeAll() {
		list.clear();
	}

	public void updateValidity(boolean value) {
		if (value) {
			checkValidity();
		} else {
			setValidity(false);
		}
	}

	protected void checkValidity() {
		for (IValidity iv : list) {
			if (!iv.getValidity()) {
				setValidity(false);
				return;
			}
		}
		setValidity(true);
	}

	protected void setValidity(boolean value) {
		for (IEnable ie : listEnablable) {
			ie.setEnabled(value);
		}
	}

}
